package tools.texture.controller {
	import kiwi.action.queue.AsyncQueue;
	import kiwi.event.ActionEvent;

	import tools.model.EditorConfig;
	import tools.model.FrameInfo;
	import tools.model.TileInfo;
	import tools.texture.controller.action.TuneTileAction;

	import org.robotlegs.mvcs.Command;

	/**
	 * 优化Tile素材
	 * @author zhangming.luo
	 */
	public class TuneTextureCommand extends Command {
		[Inject]
		public var config : EditorConfig;
		private var newTileList : Array;
		private var queue : AsyncQueue;
		private var allAction : Array = [];

		override public function execute() : void {
			newTileList = [];
			queue = new AsyncQueue(null);
			for each (var tile:TileInfo in config.allTileList) {
				var action : TuneTileAction = new TuneTileAction(tile);
				allAction.push(action);
				queue.submit(action);
			}
			queue.addEventListener(ActionEvent.ACTION_COMPLETE, onComplete);
			queue.execute();
		}

		private function onComplete(event : ActionEvent) : void {
			// 重置原有的
			var newTileList : Array = [];
			var newFrameList : Array = [];
			var cnt : int = 0;
			for each (var action:TuneTileAction in allAction) {
				var frameInfo : FrameInfo = new FrameInfo();
				frameInfo.name = action.tile.name;
				frameInfo.$source = config.texture;
				frameInfo.id = ++cnt;
				for each (var tileInfo:TileInfo in action.newTiles) {
					tileInfo.id = ++cnt;
					newTileList.push(tileInfo);
					frameInfo.tileList.push(tileInfo);
				}
				newFrameList.push(frameInfo);
			}
			config.allTileList = newTileList;
			config.allFrameList = newFrameList;
		}
	}
}
